package com.yimi.yinhepda.views.check_balance;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.liji.imagezoom.util.ImageZoom;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;
import com.yaohua.bluetoothlib.method.WeighBean;
import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.check_balance.GlideSimpleAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.CheckBalanceTableDao;
import com.yimi.yinhepda.db.table.CheckBalanceTable;
import com.yimi.yinhepda.entity.problem.ProblemBean;
import com.yimi.yinhepda.entity.request.AginWeighVolumn;
import com.yimi.yinhepda.entity.response.DataDoubleResponse;
import com.pda.ym.entity.bean.ImageInfo;
import com.pda.ym.entity.bean.ImageInfoResponse;
import com.yimi.yinhepda.entity.response.QueryAginWeighResponse;
import com.yimi.yinhepda.entity.response.QueryProblemInfoResponse;
import com.yimi.yinhepda.entity.response.QueryWybillExtendVoByWaybillNoArrayResponse;
import com.yimi.yinhepda.entity.response.WaybillExtend;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.service.CommonService;
import com.yimi.yinhepda.utils.BitmapUtils;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.yimi.yinhepda.utils.GlideImageLoader;
import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.utils.TipHelper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 复秤检查界面
 *
 * @author 000432
 * @date 2018/1/2 0002
 */
public class CheckBalanceActivity extends BaseActivity implements View.OnTouchListener {

    /**
     * 蓝牙按钮
     */
    private ImageView mBuletooth;
    /**
     * 重量计算按钮
     */
    private Button mWeightCal;
    /**
     * 体积计算按钮
     */
    private Button mVolumeCal;
    /**
     * 蓝牙连接对话框
     */
    private Dialog blueToothDialog;
    /**
     * 蓝牙条码
     */
    private TextView mBlueToothNum;
    private TextView mWayBillNum;
    /**
     * 蓝牙匹配结果
     */
    private TextView mMatchResult;
    /**
     * 总重量
     */
    private EditText mAllWeight;
    /**
     * 照片按钮
     */
    private LinearLayout mTakePhoto;
    /**
     * 图片展示器
     */
    private GridView mGridView;
    /**
     * 图片选择器
     */
    private GalleryConfig galleryConfig;
    /**
     * 选择图片路径
     */
    private List<String> pickPic;
    /**
     * 图片展示器
     */
    private GlideSimpleAdapter simpleAdapter;
    /**
     * 提交按钮
     */
    private Button mSubmit;
    /**
     * 上传图片的ID
     */
    private String mImageId = "";
    /**
     * 运单详情实体
     */
    private WaybillExtend mWaybillExtend;
    /**
     * 总体积
     */
    private EditText mAllVolume;
    /**
     * 备注
     */
    private EditText mRemark;
    /**
     * 返回按钮
     */
    private Button mBack;
    /**
     * 校验按钮
     */
    private Button mCheck;
    /**
     * 存储图片集合
     */
    private List<HashMap<String, Object>> dataList;
    /**
     * 是否体积计费标志
     */
    private boolean isVolumeCal = false;
    /**
     * 是否差重差方,1-是，2-否
     */
    private int isDiffWeight = 2;
    /**
     * 复秤合计数据显示
     */
    private TextView mTvAllCount;
    /**
     * 差重差方数据显示
     */
    private TextView mTvAllDiff;
    /**
     * 重泡比
     */
    private TextView mTvWeightVolumnRatio;
    /**
     * 计费重量显示
     */
    private TextView mTvChargeableWeight;
    private CheckBalanceTableDao checkBalanceTableDao;
    private String mUserCode;
    private String mCompCode;
    private final int PICURE_NUM = 15;

    private final int PERMISSIONS_REQUEST_READ_CONTACTS = 101;
    private final int PERMISSIONS_REQUEST_CAMERA = 102;
    boolean isGalleryConfigPick = false;
    private CommonService.IService iService;
    public static Handler handler;
    public static final int HANDLER_ONE = 1;
    public static final int HANDLER_TWO = 2;
    /**
     * 重泡比
     */
    private double wvRatio;

    @Override
    public String getPageName() {
        return "复称检查界面";
    }

    @SuppressLint("HandlerLeak")
    private void getHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLER_ONE:
                        if (mMatchResult != null) {
                            Bundle bundle = msg.getData();
                            int color = bundle.getInt("color");
                            String connResult = bundle.getString("connResult");
                            int visibility = bundle.getInt("visibility");
                            mMatchResult.setTextColor(color);
                            mMatchResult.setText(connResult);
                            mMatchResult.setVisibility(visibility);
                        }
                        break;
                    case HANDLER_TWO:
                        //蓝牙已连接
                        if (mBlueToothNum != null) {
                            String blueToothNum_sp = sharedPreferUtil.getValue(Common.BLUE_TOOTH_NUM);
                            String blueToothNum = mBlueToothNum.getText().toString();
                            if (!blueToothNum_sp.equals("") && blueToothNum_sp.equals(blueToothNum)) {
                                mBlueToothNum.setText(blueToothNum);
                            } else {
                                mBlueToothNum.setText("");
                            }
                            mMatchResult.setVisibility(View.GONE);
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        ;
    }

    public CheckBalanceActivity() {
        super(true);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        outState.putSerializable("iService", iService);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        iService = (CommonService.IService) getIntent().getSerializableExtra("iService");
        if (iService != null) {
            iService.openBluetooth();
        } else {
            showToast("蓝牙服务为空，请退出重试！");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_balance);

        iService = (CommonService.IService) getIntent().getSerializableExtra("iService");
        //打开蓝牙
        if (iService != null) {
            iService.openBluetooth();
        }
        getHandler();

        mBuletooth = findViewById(R.id.check_balance_buletooth);
        mWeightCal = findViewById(R.id.check_balance_weight_calculation);
        mVolumeCal = findViewById(R.id.check_balance_volume_calculation);
        mWayBillNum = findViewById(R.id.check_balance_wayBillNum);
        mAllWeight = findViewById(R.id.check_balance_all_weight);
        mTakePhoto = findViewById(R.id.check_balance_take_photo);
        mGridView = findViewById(R.id.check_balance_gv_pic);
        mSubmit = findViewById(R.id.check_balance_submit);
        mAllVolume = findViewById(R.id.check_balance_all_volumn);
        mRemark = findViewById(R.id.check_balance_remark);
        mBack = findViewById(R.id.check_balance_back);
        mCheck = findViewById(R.id.check_balance_check);
        mTvAllCount = findViewById(R.id.check_balance_all_count);
        mTvAllDiff = findViewById(R.id.check_balance_all_diff);
        //重泡比
        mTvWeightVolumnRatio = findViewById(R.id.tv_weightVolumnRatio);
        //计费重量
        mTvChargeableWeight = findViewById(R.id.tv_chargeableWeight);

        mBuletooth.setOnClickListener(this);
        mWeightCal.setOnClickListener(this);
        mVolumeCal.setOnClickListener(this);
        mTakePhoto.setOnClickListener(this);
        mSubmit.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mCheck.setOnClickListener(this);

        checkBalanceTableDao = new CheckBalanceTableDao();
        mUserCode = sharedPreferUtil.getValue(Common.USER_CODE);
        mCompCode = sharedPreferUtil.getCompanyCode();

        //获取复秤合计和差重差方数据
        getDataCount();

        //总重量设置小数点保留一位
        mAllWeight.setFilters(new InputFilter[]{
                new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                        if (".".equals(source) && dest.toString().length() == 0) {
                            return "0.";
                        }
                        if (dest.toString().contains(".")) {
                            int index = dest.toString().indexOf(".");
                            int length = dest.toString().substring(index).length();
                            if (length == 2) {
                                return "";
                            }
                        }
                        return null;
                    }
                }
        });

        //总体积设置小数点保留两位
        mAllVolume.setFilters(new InputFilter[]{
                new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                        if (source.equals(".") && dest.toString().length() == 0) {
                            return "0.";
                        }
                        if (dest.toString().contains(".")) {
                            int index = dest.toString().indexOf(".");
                            int length = dest.toString().substring(index).length();
                            if (length == 3) {
                                return "";
                            }
                        }
                        return null;
                    }
                }
        });

        mAllWeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String allWeight = mAllWeight.getText().toString();
                if (!allWeight.contains(".")) {
                    if (allWeight.length() > 6) {
                        allWeight = allWeight.substring(0, 6);
                        mAllWeight.setText(allWeight);
                        mAllWeight.setSelection(mAllWeight.length());
                    }
                }
            }
        });

        mAllVolume.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                boolean isFourNum = false;
                String allVloumn = mAllVolume.getText().toString();
                if (!allVloumn.contains(".")) {
                    if (allVloumn.length() > 3) {
                        isFourNum = true;
                        allVloumn = allVloumn.substring(0, 3);
                        mAllVolume.setText(allVloumn);
                        mAllVolume.setSelection(mAllVolume.length());
                    }
                }
                if (!isFourNum) {
                    try {
                        double vlo = Double.parseDouble(allVloumn);
                        if (vlo >=10) {
                            MyDialog.showAlertDialog(CheckBalanceActivity.this, "您输入的实际体积大于等于10，请核实是否填写有误！");
                            SoundVibratorManager.playSound(2);
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        pickPic = new ArrayList<>();
        dataList = new ArrayList<>();

        simpleAdapter =
                new GlideSimpleAdapter(this, dataList, R.layout.gridview_item1, new String[]{"itemImage"}, new int[]{R.id.imageView2}, pickPic);
        mGridView.setAdapter(simpleAdapter);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ImageZoom.show(CheckBalanceActivity.this, i, pickPic);
            }
        });
        mGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                //震动
                TipHelper.Vibrate(CheckBalanceActivity.this, 500);
                MyDialog deleteDialog = new MyDialog(CheckBalanceActivity.this);
                deleteDialog.setIcon(R.drawable.alert);
                deleteDialog.setMessage("确定删除该图片吗?");
                deleteDialog.setPositiveClickListener( "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        dataList.remove(position);
                        pickPic.remove(position);
                        List<String> tempPickPic = new ArrayList<>();
                        tempPickPic.addAll(pickPic);
                        resetPicture(tempPickPic);
                    }
                });
                deleteDialog.setNegativeClickListener(R.drawable.btn_cancel_selector, "取消", null);
                deleteDialog.show();

                return true;
            }
        });

        //初始化图片选择框架
        galleryConfig = new GalleryConfig.Builder()
                // 监听接口（必填）
                .iHandlerCallBack(iHandlerCallBack)
                // provider (必填)
                .imageLoader(new GlideImageLoader()).provider("com.yimi.yinhepda.fileprovider")
                // 记录已选的图片
                .pathList(pickPic)
                // 配置是否多选的同时 配置多选数量   默认：false
                .multiSelect(true, PICURE_NUM)
                // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(false)
                // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .crop(false, 1, 1, 500, 500)
                // 是否实现相机按钮  默认：false
                .isShowCamera(true)
                // 图片存放路径
                .filePath("/Gallery/Pictures").build();

        //请求相机权限
        requestCameraPermission();
    }

    public static byte[] getBytes(InputStream is) throws IOException {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024]; // 用数据装
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            outstream.write(buffer, 0, len);
        }
        outstream.close();
        // 关闭流一定要记得。
        return outstream.toByteArray();
    }

    /**
     * 请求相机权限
     */
    private void requestCameraPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CAMERA);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.check_balance_buletooth:
                //蓝牙对话框
                bluetoothConnectDialog();
                break;
            case R.id.check_balance_weight_calculation:
                //重量计算对话框
                weightCalculationDialog();
                break;
            case R.id.check_balance_volume_calculation:
                //体积计算对话框
                volume_calculationDialog();
                break;
            case R.id.check_balance_take_photo:
                //拍照功能
                takePhotoFunction();
                break;
            case R.id.check_balance_submit:
                //提交按钮
                boolean isDiff = checkFunction(false);
                if (isDiff) {
//                    boolean exitData = checkBalanceTableDao.exitWayBillData(mUserCode, mCompCode, mWaybillExtend.getWaybillNo() + "");
//                    if (exitData) {
//                        showToast("该运单号已提交！");
//                    } else {
                    //无差重差方，则正常提交
                    MyDialog deleteDialog = new MyDialog(CheckBalanceActivity.this);
                    deleteDialog.setTitle("系统提示");
                    deleteDialog.setIcon(R.drawable.alert);
                    deleteDialog.setMessage("数据提交后不可修改！");
                    deleteDialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            uploadImage();
                        }
                    });
                    deleteDialog.setNegativeClickListener(R.drawable.btn_confirm_selector, "取消", null);
                    deleteDialog.show();
//                    }
                }
                break;
            case R.id.check_balance_back:
                finish();
                break;
            case R.id.check_balance_check:
                checkFunction(true);
                break;
            default:
                break;
        }
    }

    /**
     * 检验是否差重差方功能
     * 返回true，则无差重差方
     */

    private boolean checkFunction(boolean isCheck) {
        if (mWaybillExtend == null) {
            showToast("运单未扫描！");
            return false;
        }
        String allVolume = mAllVolume.getText().toString().trim();
        String allWeight = mAllWeight.getText().toString().trim();
        if (isVolumeCal) {
            if ("".equals(allVolume)) {
                showToast("请填写体积！");
                return false;
            }
        } else {
            if ("".equals(allWeight)) {
                showToast("请填写重量！");
                return false;
            }
        }
        //至少上传一张照片
        if (!isCheck) {
            if (pickPic != null && pickPic.size() < 1) {
                MyDialog myDialog = new MyDialog(this);
                myDialog.setTitle("系统提示");
                myDialog.setTextColor(R.color.red);
                myDialog.setIcon(R.drawable.alert);
                myDialog.setPositiveClickListener( "拍照", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //直接开启相机
                        GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(CheckBalanceActivity.this);
                    }
                });
                myDialog.setNegativeClickListener(R.drawable.btn_confirm_selector, "知道了", null);
                myDialog.setCanceledOnTouchOutside(false);
                myDialog.setMessage("照片为必填项，请至少上传一张照片！");
                try {
                    myDialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }
        }
        if (pickPic != null) {
            for (int i = 0; i < pickPic.size(); i++) {
                try {
                    BitmapUtils.decodeSampledBitmapFromFile(pickPic.get(i), 600, 400);
                } catch (Exception e) {
                    showToast("第" + (i + 1) + "张图片已损坏，请删除重新选择！");
                    return false;
                }
            }
        }
        //输入体积
        double balanceAllVolume = Double.parseDouble(allVolume.equals("") ? "0" : allVolume);
        if (balanceAllVolume > 100) {
            MyDialog.showAlertDialog(this, "货物体积不能大于100m³");
            SoundVibratorManager.playSound(2);
            return false;
        }
        //输入重量
        double balanceAllWeight = Double.parseDouble(allWeight.equals("") ? "0" : allWeight);
//        1.折算后重量(kg)=实际体积(m³)*100万/重泡比(cm³/kg) ,需与手输重量进行对比，取数值大的为重量,（重量-开单计费重量）/开单计费重量x100）>=5%
        double diffWeight = 0;
        double tempWight = 0;
        if (balanceAllVolume != 0 && wvRatio != 0) {
            //折算后重量(kg)=实际体积(m³)*100万/重泡比(cm³/kg)
            tempWight = (balanceAllVolume * 1000000) / wvRatio;
        }
        if (tempWight < balanceAllWeight) {
            tempWight = balanceAllWeight;
        }
        //开单计费重量
        double billChargeWeight = Double.parseDouble(mWaybillExtend.getChargeableWeight() + "");
        if (tempWight != 0 && billChargeWeight != 0) {
            diffWeight = StringUtils.div(StringUtils.sub(tempWight, billChargeWeight), billChargeWeight);
        }
        //2.（输入重量-开单实际重量）/开单实际重量 x100）>=20% || (输入重量-开单实际重量）/开单实际重量 x100）<= -20%
        //  （输入体积-开单体积）/开单体积 x100）>=20% || (输入体积-开单体积）/开单体积 x100）<= -20%
        //开单实际重量
        double billWeights = Double.parseDouble(mWaybillExtend.getRealWeight() + "");
        double diffWeight2 = 0;
        if (balanceAllWeight != 0 && billWeights != 0) {
            diffWeight2 = StringUtils.div(StringUtils.sub(balanceAllWeight, billWeights), billWeights);
        }
        //开单体积
        double billVolume = Double.parseDouble(mWaybillExtend.getVolume() + "");
        double diffVolume2 = 0;
        if (balanceAllVolume != 0 && billVolume != 0) {
            diffVolume2 = StringUtils.div(StringUtils.sub(balanceAllVolume, billVolume), billVolume);
        }
        String content = "";
        if (diffWeight >= 0.05) {
            content = "此货物存在差重差方！";
        } else {
            //百分之20
            double p20 = 0.2;
            //体积计费优先校验体积,再校验重量
            if (isVolumeCal) {
                //体积计费，输入体积和开单体积不相等则校验
                if (balanceAllVolume != mWaybillExtend.getVolume().doubleValue()) {
                    //输入体积和开单体积不相等则校验
                    if (diffVolume2 >= p20 || diffVolume2 <= -p20) {
                        content = "此货物存在差重差方！(非计费重)";
                    } else if (balanceAllWeight != mWaybillExtend.getRealWeight().doubleValue()) {
                        //输入重量和开单重量不相等则校验
                        if (diffWeight2 >= p20 || diffWeight2 <= -p20) {
                            content = "此货物存在差重差方！(非计费重)";
                        }
                    }
                } else if (balanceAllWeight != mWaybillExtend.getRealWeight().doubleValue()) {
                    //输入重量和开单重量不相等则校验
                    if (diffWeight2 >= p20 || diffWeight2 <= -p20) {
                        content = "此货物存在差重差方！(非计费重)";
                    }
                }
            } else {
                if (balanceAllWeight != mWaybillExtend.getRealWeight().doubleValue()) {
                    //输入重量和开单重量不相等则校验
                    if (diffWeight2 >= p20 || diffWeight2 <= -p20) {
                        content = "此货物存在差重差方！(非计费重)";
                    } else if (balanceAllVolume != mWaybillExtend.getVolume().doubleValue()) {
                        //输入体积和开单体积不相等则校验
                        if (diffVolume2 >= p20 || diffVolume2 <= -p20) {
                            content = "此货物存在差重差方！(非计费重)";
                        }
                    }
                } else if (balanceAllVolume != mWaybillExtend.getVolume().doubleValue()) {
                    //输入体积和开单体积不相等则校验
                    if (diffVolume2 >= p20 || diffVolume2 <= -p20) {
                        content = "此货物存在差重差方！(非计费重)";
                    }
                }
            }
        }
        if (!"".equals(content)) {
            //是差重差方标志
            isDiffWeight = 1;
            MyDialog myDialog = new MyDialog(this);
            myDialog.setTitle("系统提示");
            myDialog.setTextColor(R.color.red);
            myDialog.setIcon(R.drawable.alert);
            myDialog.setPositiveClickListener( "拍照", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    //直接开启相机
                    GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(CheckBalanceActivity.this);
                }
            });
            myDialog.setNegativeClickListener(R.drawable.btn_confirm_selector, "知道了", null);
            myDialog.setCanceledOnTouchOutside(false);
            if (isCheck) {
                myDialog.setMessage(content);
                myDialog.show();
            } else {
                //点击提交时提示内容
                if (pickPic != null && pickPic.size() < 1) {
                    myDialog.setMessage("照片为必填项，请至少上传一张照片！");
                    myDialog.show();
                } else {
                    return true;
                }
            }
            return false;
        } else {
            //不是差重差方标志
            isDiffWeight = 2;
            if (isCheck) {
                final MyDialog myDialog = new MyDialog(this);
                myDialog.setTitle("系统提示");
                myDialog.setTextColor(R.color.colore1d9717);
                myDialog.setMessage("此货物正常！");
                myDialog.setIcon(R.drawable.alert);
                myDialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        myDialog.dismiss();
                    }
                }, 2 * 1000);
            }
        }
        return true;
    }

    /**
     * 图片上传
     */
    private void uploadImage() {
        if (pickPic != null && pickPic.size() > 0) {
            if (pickPic.size() > PICURE_NUM) {
                showToast("图片不可大于" + PICURE_NUM + "张！");
                return;
            }
            showPgDlg("正在上传图片数据...");
            Map param = new HashMap();
            //4为图片上传格式规范ID，8为视频上传规范ID
            param.put("uploaderStrategyId", "4");

            NetRequest request = new NetRequest();
            for (int i = 0; i < pickPic.size(); i++) {
                String item = pickPic.get(i);
                String fileName = item.substring(item.lastIndexOf("/") + 1);
                request.addFile("file" + i, fileName, new File(item));
            }
            request.setParams(param)
                    .setMethod(NetRequest.Method.POST)
                    .setUrl(Constants.URL_UPLOAD_IMAGE)
                    .setResponsClazz(ImageInfoResponse.class)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            setScannerEnabled(true);
                            dismissPgDlg();
                            SoundVibratorManager.playSound(2);
                            if (msg != null) {
                                showToast("图片上传失败:" + msg);
                            } else {
                                showToast("图片上传失败!");
                            }
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            ImageInfoResponse response = (ImageInfoResponse) obj;
                            mImageId = "";
                            for (ImageInfo item : response.getData()) {
                                mImageId += (item.getFileKey() + ",");
                            }
                            mImageId = mImageId.substring(0, mImageId.length() - 1);
                            //复秤检查提交
                            checkBalanceSubmit();
                        }
                    });
        } else {
            //复秤检查提交
            checkBalanceSubmit();
        }
    }

    /**
     * 复秤检查提交
     */
    private void checkBalanceSubmit() {
        AginWeighVolumn requestBean = new AginWeighVolumn();
        requestBean.setWaybillNo(mWaybillExtend.getWaybillNo() + "");
        requestBean.setOperDeptCode(sharedPreferUtil.getDeptCode());
        requestBean.setScanTime(DateHelper.getDateTimeFormateForSimple(new Date()));
        requestBean.setCompCode(sharedPreferUtil.getCompanyCode());
        requestBean.setOperEmpCode(sharedPreferUtil.getValue(Common.USER_CODE));
        requestBean.setSrcZoneCode(mWaybillExtend.getSourceZoneCode());
        String waybillTime = DateHelper.formatTimeEight2(mWaybillExtend.getCreaterTime());
        requestBean.setWayBillTime(waybillTime);
        requestBean.setBillWeight(mWaybillExtend.getRealWeight());
        requestBean.setBillVolumn(mWaybillExtend.getVolume());
        String allWeight = mAllWeight.getText().toString().trim();
        if (allWeight.equals("")) {
            allWeight = "0";
        }
        requestBean.setAginWeight(new BigDecimal(allWeight));
        String allVolume = mAllVolume.getText().toString().trim();
        if (allVolume.equals("")) {
            allVolume = "0";
        }
        requestBean.setAginVolumn(new BigDecimal(allVolume));
        requestBean.setBeDifference(isDiffWeight);
        requestBean.setImageInfo(mImageId);
        requestBean.setRemarks(mRemark.getText().toString().trim());

        showPgDlg("正在提交数据...");
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(Object.class)
                .setUrl(Constants.URL_UP_AGIN_WEIGHT)
                .setRequestObject(requestBean)
                .setConnTimeOut(5 * 1000)
                .execute(new UICallBack() {

                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast("数据提交失败：" + msg);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        CheckBalanceTable bean = new CheckBalanceTable();
                        bean.setUserCode(mUserCode);
                        bean.setCompCode(mCompCode);
                        bean.setWayBillNum(mWaybillExtend.getWaybillNo() + "");
                        if (isDiffWeight == 1) {
                            //设置为差重差方类型
                            bean.setStatisticsType(2);
                        } else {
                            //设置为复秤合计类型
                            bean.setStatisticsType(1);
                        }
                        try {
                            checkBalanceTableDao.insert(bean);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                        //获取复秤合计和差重差方数据
                        getDataCount();
                        resetPicture(null);
                        showToast("数据提交成功！");
                        SoundVibratorManager.playSound(1);
                        recoveryWidgetStatus();
                    }
                });
    }

    /**
     * 恢复控件状态
     */
    private void recoveryWidgetStatus() {
        mAllWeight.setEnabled(true);
        mAllVolume.setEnabled(true);
        mWeightCal.setEnabled(true);
        mVolumeCal.setEnabled(true);
        //清除界面数据
        mWayBillNum.setText("");
        mAllWeight.setText("");
        mAllVolume.setText("");
        mRemark.setText("");
        mTvWeightVolumnRatio.setText("");
        mTvChargeableWeight.setText("");
    }

    /**
     * 拍照选择图片功能
     */
    private void takePhotoFunction() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permission != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
                } else {
                    //提示手动打开读写权限
                    Common.showPermissionDialog(CheckBalanceActivity.this, "程序需要打开读写存储权限，才能正常使用！", null);
                }
                return;
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CAMERA);
                } else {
                    //提示手动打开相机权限
                    Common.showPermissionDialog(CheckBalanceActivity.this, "程序需要打开相机权限，才能正常使用！", null);
                }
                return;
            }
        }
        galleryConfig.getBuilder().isOpenCamera(false).build();
        galleryConfig.getBuilder().pathList(pickPic);
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(this);
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            doScan(result);
        }
    }

    /**
     * 扫描条码
     */
    private void doScan(String result) {
        if (blueToothDialog != null && blueToothDialog.isShowing()) {
            /**扫描获取蓝牙条码*/
            if (mBlueToothNum != null) {
                int startCount = 0;
                int endCount = 2;
                StringBuilder tempResult = new StringBuilder();
                while (startCount < result.length()) {
                    if (endCount >= result.length()) {
                        endCount = result.length();
                    }
                    tempResult.append(result.substring(startCount, endCount) + ":");
                    startCount = startCount + 2;
                    endCount = endCount + 2;
                }
                String tempResultStr = tempResult.substring(0, tempResult.length() - 1);
                mBlueToothNum.setText(tempResultStr);
                mMatchResult.setVisibility(View.VISIBLE);
                mMatchResult.setTextColor(Color.BLACK);
                mMatchResult.setText("蓝牙配对中...");
                iService.connectBlueToothDevice(tempResultStr);
                //bluetoothManager.connectDevice("00:15:83:45:63:FD");
            }
        } else {
            /**扫描获取运单条码*/
            if (result.length() > 12) {
                result = result.substring(0, 12);
            } else if (result.length() != 12) {
                showToast("运单号不规范!");
                SoundVibratorManager.playSound(2);
                return;
            }
            mWayBillNum.setText(result);
            //调用运营接口查询运单是否被上传过
            queryWaybillUpload(result);
        }
    }

    /**
     * 运营接口：查询运单是否已经上传
     */
    private void queryWaybillUpload(final String waybill) {
        showPgDlg("正在查询...");
        Map<String, String> params = new HashMap<>();
        params.put("waybillNo", waybill);
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryAginWeighResponse.class)
                .setUrl(Constants.URL_QUERY_AGIN_WAYBILLNO)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        LogUtil.e("运营接口查询运单失败：" + msg);
                        //调用质控接口查询运单是否被上传过
                        queryQcUploadWaybill(waybill);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryAginWeighResponse response = (QueryAginWeighResponse) obj;
                        if (response.isData()) {
                            MyDialog.showAlertDialog2(CheckBalanceActivity.this, "提示", "此票货已上报过差重差方！", "确定");
                            queryWaybillDetail(waybill);
                        } else {
                            //调用质控接口查询运单是否被上传过
                            queryQcUploadWaybill(waybill);
                        }
                    }
                });
    }

    /**
     * 调用质控接口查询运单是否被上传过
     */
    private void queryQcUploadWaybill(final String waybill) {
        showPgDlg("正在查询...");
        Map<String, String> params = new HashMap<>();
        params.put("currentPage", 1 + "");
        params.put("pageSize", 100 + "");
        params.put("waybillNo", waybill);
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryProblemInfoResponse.class)
                .setUrl(Constants.URL_QC_2_ABNORMALAPPPAGE)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        LogUtil.e("质控接口查询运单失败：" + msg);
                        queryWaybillDetail(waybill);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryProblemInfoResponse response = (QueryProblemInfoResponse) obj;
                        List<ProblemBean> beans = response.getData().getPage().getRecords();
                        for (ProblemBean bean : beans) {
                            if ("W117".equals(bean.getAbnormalCategory())) {
                                //判断是差重差方类型，则提示
                                MyDialog.showAlertDialog2(CheckBalanceActivity.this, "提示", "此票货已上报过差重差方！", "确定");
                                break;
                            }
                        }
                        queryWaybillDetail(waybill);
                    }
                });
    }

    /**
     * 查询运单详情
     */
    private void queryWaybillDetail(final String waybill) {
        showPgDlg("正在查询...");

        Map<String, String> params = new HashMap<>(1);
        params.put("waybillNoArray", waybill);

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryWybillExtendVoByWaybillNoArrayResponse.class)
                .setUrl(Constants.URL_GETWAYBILL)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        showToast("加载数据失败：" + msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        //恢复控件状态
                        recoveryWidgetStatus();
                        if (obj instanceof QueryWybillExtendVoByWaybillNoArrayResponse) {
                            QueryWybillExtendVoByWaybillNoArrayResponse response = (QueryWybillExtendVoByWaybillNoArrayResponse) obj;
                            if (response.getData().getWaybillExtendList() != null) {
                                mWayBillNum.setText(waybill);
                                isVolumeCal = false;
                                mWaybillExtend = response.getData().getWaybillExtendList().get(0);
                                mTvChargeableWeight.setText(mWaybillExtend.getChargeableWeight().toString() + "KG");
                                BigDecimal realWeight = mWaybillExtend.getRealWeight();
                                BigDecimal chargeableWeight = mWaybillExtend.getChargeableWeight();
                                //进位取整：实重小数点后1位进1，例如：3.1进1后为4
                                BigDecimal tempRealWeight = new BigDecimal(Math.ceil(Double.parseDouble(realWeight.toString())));
                                //大于返回1，等于返回0，小于返回-1
                                if (chargeableWeight.compareTo(tempRealWeight) == 1) {
                                    //计费重量大于重量为【体积计费】
                                    MyDialog.showAlertDialog(CheckBalanceActivity.this, "系统提示", "此票货需复检体积！", "确认");
                                    //重量输入框和重量计算按钮置灰
//                                    mAllWeight.setEnabled(false);
//                                    mWeightCal.setEnabled(false);
                                    //设置运单开单实重，小数点后保留1位
                                    DecimalFormat df = new java.text.DecimalFormat("#.#");
                                    mAllWeight.setText(df.format(realWeight));
                                    //是体积计费标志
                                    isVolumeCal = true;
                                } else {
                                    //计费重量小于等于重量为【重量计费】
                                    //体积输入框和体积计算按钮置灰
//                                    mAllVolume.setEnabled(false);
//                                    mVolumeCal.setEnabled(false);
                                    //设置运单开单体积，小数点后保留2位
                                    DecimalFormat df = new java.text.DecimalFormat("#.##");
                                    mAllVolume.setText(df.format(mWaybillExtend.getVolume()));
                                    //获取复秤重量
                                    WeighBean weigh = iService.getWeight();
                                    if (weigh != null && weigh.getTimes() >= 5) {
                                        //四舍五入，保留一位
                                        double rWeight = roundingNum(Double.parseDouble(weigh.getWeigh()), 1);
                                        mAllWeight.setText(rWeight + "");
                                        Log.e(">>>>>>>>", "稳定: " + weigh.toString());
                                    } else {
                                        Log.e(">>>>>>>>", "未稳定: " + weigh);
                                    }
                                }
                                SoundVibratorManager.playSound(1);
                                //计费重量取整
                                DecimalFormat df = new java.text.DecimalFormat("#");
                                mTvChargeableWeight.setText(String.format("%s", df.format(mWaybillExtend.getChargeableWeight().doubleValue()) + " kg"));
                                //调用重泡比接口获取重泡比
                                getChargeableWeight(mWaybillExtend);
                            } else {
                                mWayBillNum.setText("");
                                showToast("无该运单的信息");
                                SoundVibratorManager.playSound(2);
                            }
                        }
                    }
                });
    }

    /**
     * 获取重泡比
     */
    private void getChargeableWeight(final WaybillExtend waybillExtend) {
        wvRatio = 0;
        Map<String, String> params = new HashMap<>(7);
        //经营属性
        params.put("businessType", waybillExtend.getBusinessModel().toString());
        //始发公司code
        params.put("compCode", waybillExtend.getCompCode());
        //货物code
        params.put("consignCode", waybillExtend.getConsignCode());
        //目的网点code
        params.put("destZoneCode", waybillExtend.getDestZoneCode());
        //目的公司code
        params.put("endCompCode", waybillExtend.getToCompCode());
        //体积
        params.put("ratioValue", waybillExtend.getVolume().toString());
        //始发网点code
        params.put("sourceZoneCode", waybillExtend.getSourceZoneCode());
        //开单时间
        params.put("waybillTime", waybillExtend.getCreaterTime());

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(DataDoubleResponse.class)
                .setUrl(Constants.URL_QUERY_WEIGHT_VOLUMN_RATIO)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {

                    }

                    @Override
                    public void onSuccess(Object obj) {
                        DataDoubleResponse response = (DataDoubleResponse) obj;
                        if (response != null) {
                            wvRatio = response.getData();
                            //重泡比小数点后保留两位
                            DecimalFormat df = new java.text.DecimalFormat("#.##");
                            mTvWeightVolumnRatio.setText(String.format("%s", df.format(response.getData()) + " cm³/kg"));
                        }
                    }
                });
    }

    /**
     * 图片加载框架，返回图接口
     */
    IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
        @Override
        public void onStart() {
            LogUtil.e("onStart: 开启");
        }

        @Override
        public void onSuccess(List<String> photoList) {
            LogUtil.e("onSuccess: 返回数据");
            for (String s : photoList) {
                LogUtil.e(s);
            }
            resetPicture(photoList);
        }

        @Override
        public void onCancel() {
            LogUtil.e("onCancel: 取消");
        }

        @Override
        public void onFinish() {
            LogUtil.e("onFinish: 结束");
        }

        @Override
        public void onError() {
            LogUtil.e("onError: 出错");
        }
    };

    private void resetPicture(List<String> photoList) {

        pickPic.clear();
        dataList.clear();

        if (photoList != null && photoList.size() > 0) {
            pickPic.addAll(photoList);
        }

        if (photoList != null) {
            for (int i = 0; i < photoList.size(); i++) {
                LogUtil.e(photoList.get(i));
                HashMap<String, Object> gridviewItem = new HashMap<>();
                gridviewItem.put("itemImage", photoList.get(i));
                dataList.add(gridviewItem);
            }
        }

        simpleAdapter.notifyDataSetChanged();

        if (!isGalleryConfigPick) {
            galleryConfig.getBuilder().pathList(pickPic);
        }
        isGalleryConfigPick = false;

    }

    /**
     * 蓝牙连接对话框
     */
    private void bluetoothConnectDialog() {
        LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.alert_dialog_bluetooth_match, null);
        Button confirm = layout.findViewById(R.id.bluetooth_match_confirm);
        mBlueToothNum = layout.findViewById(R.id.bluetooth_match_num);
        mMatchResult = layout.findViewById(R.id.bluetooth_match_result);
        blueToothDialog = new Dialog(this, R.style.AsyncTaskDialog);
        blueToothDialog.addContentView(layout,
                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        blueToothDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        blueToothDialog.getWindow().getDecorView().setPadding(10, 0, 10, 0);
        blueToothDialog.setCanceledOnTouchOutside(false);
        blueToothDialog.show();

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                blueToothDialog.dismiss();
            }
        });
    }

    /**
     * 重量计算对话框
     */
    private void weightCalculationDialog() {
        final LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.alert_dialog_weight_calculation, null);
        final LinearLayout layoutAdd = layout.findViewById(R.id.weight_calculation_layout_add);
        //总重量
        final TextView tvAllWeight = layout.findViewById(R.id.weight_calculation_all_weight);
        //添加按钮
        Button wcAdd = layout.findViewById(R.id.weight_calculation_add);
        //删除按钮
        Button wcRedeuc = layout.findViewById(R.id.weight_calculation_reduce);
        //计算按钮
        Button btnCal = layout.findViewById(R.id.weight_calculation_cal);
        //确定按钮
        Button btnOK = layout.findViewById(R.id.weight_calculation_ok);
        //关闭窗口按钮
        ImageView closeDialog = layout.findViewById(R.id.weight_calculation_cancle);
        final Dialog dialog = new Dialog(this, R.style.AsyncTaskDialog);
        dialog.addContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.getWindow().getDecorView().setPadding(10, 0, 10, 0);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        final List<LinearLayout> layoutItems = new ArrayList<>();
        LinearLayout layoutItem = getWeightLayoutItem();
        layoutAdd.addView(layoutItem);
        layoutItems.add(layoutItem);

        wcAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout layoutItem = getWeightLayoutItem();
                layoutAdd.addView(layoutItem);
                layoutItems.add(layoutItem);
            }
        });

        wcRedeuc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (layoutItems != null && layoutItems.size() > 1) {
                    layoutAdd.removeViewAt(layoutItems.size() - 1);
                    layoutItems.remove(layoutItems.size() - 1);
                }
            }
        });

        btnCal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double allWeight = 0.0;
                //计算总重量
                for (LinearLayout itemLayout : layoutItems) {
                    //单件重
                    EditText et_single = itemLayout.findViewById(R.id.weight_item_single);
                    //数量
                    EditText et_num = itemLayout.findViewById(R.id.weight_item_num);

                    String single = et_single.getText().toString().trim();
                    String num = et_num.getText().toString().trim();
                    if (!single.equals("") && !num.equals("")) {
                        double weight = 0;
                        try {
                            weight = Double.parseDouble(single) * Long.parseLong(num);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            showToast("数据异常！");
                            return;
                        }
                        //四舍五入，保留一位
                        allWeight += roundingNum(weight, 1);
                    }
                }
                tvAllWeight.setText(allWeight + "");
            }
        });

        btnOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String allWeight = tvAllWeight.getText().toString().trim();
                if (!allWeight.equals("")) {
                    double tempWeight = Double.parseDouble(allWeight);
                    if (tempWeight >= 0 && tempWeight <= 999999) {
                        mAllWeight.setText(allWeight);
                    } else {
                        //总值不超过999999kg
                        showToast("总值不可超过999999kg");
                        return;
                    }
                }
                dialog.dismiss();
            }
        });

        closeDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 重量计算中的子布局
     */
    private LinearLayout getWeightLayoutItem() {
        LinearLayout layoutItem = (LinearLayout) LayoutInflater.from(CheckBalanceActivity.this).inflate(R.layout.weight_calculation_item, null);
        //单件重
        final EditText et_single = (EditText) layoutItem.findViewById(R.id.weight_item_single);
        //数量
        EditText num = (EditText) layoutItem.findViewById(R.id.weight_item_num);

        et_single.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String single = et_single.getText().toString();
                if (!single.contains(".")) {
                    if (single.length() > 6) {
                        single = single.substring(0, 6);
                        et_single.setText(single);
                        et_single.setSelection(et_single.length());
                    }
                }
            }
        });
        return layoutItem;
    }

    /**
     * 体积计算对话框
     */
    private void volume_calculationDialog() {
        LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.alert_dialog_volume_calculation, null);
        final TextView tvAllVolume = layout.findViewById(R.id.volume_calculation_allVolume);
        final LinearLayout layoutAdd = layout.findViewById(R.id.volume_calculation_add_layout);
        Button vcAdd = layout.findViewById(R.id.volume_calculation_add);
        Button vcReduce = layout.findViewById(R.id.volume_calculation_reduce);
        Button btnCal = layout.findViewById(R.id.volume_calculation_cal);
        Button btnOK = layout.findViewById(R.id.volume_calculation_ok);
        ImageView cancle = layout.findViewById(R.id.volume_calculation_cancle);
        final Dialog dialog = new Dialog(this, R.style.AsyncTaskDialog);
        dialog.addContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.getWindow().getDecorView().setPadding(10, 0, 10, 0);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        final List<LinearLayout> layoutItems = new ArrayList<>();
        LinearLayout layoutItem = getVolumnLayoutItem();
        layoutAdd.addView(layoutItem);
        layoutItems.add(layoutItem);

        vcAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout layoutItem = getVolumnLayoutItem();
                layoutAdd.addView(layoutItem);
                layoutItems.add(layoutItem);
            }
        });

        vcReduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (layoutItems != null && layoutItems.size() > 1) {
                    layoutAdd.removeViewAt(layoutItems.size() - 1);
                    layoutItems.remove(layoutItems.size() - 1);
                }
            }
        });

        btnCal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double allVolumn = 0.0;
                //计算总体积
                for (LinearLayout itemLayout : layoutItems) {
                    //体积长
                    EditText et_long = (EditText) itemLayout.findViewById(R.id.volume_cal_long);
                    //体积宽
                    EditText et_wide = (EditText) itemLayout.findViewById(R.id.volume_cal_wide);
                    //体积高
                    EditText et_height = (EditText) itemLayout.findViewById(R.id.volume_cal_height);
                    //数量
                    EditText et_num = (EditText) itemLayout.findViewById(R.id.volume_cal_num);

                    String longStr = et_long.getText().toString().trim();
                    String wideStr = et_wide.getText().toString().trim();
                    String heightStr = et_height.getText().toString().trim();
                    String numStr = et_num.getText().toString().trim();
                    if (!longStr.equals("") && !wideStr.equals("") && !heightStr.equals("") && !numStr.equals("")) {
                        try {
                            double tmepVolumn = Double.parseDouble(longStr) * Double.parseDouble(wideStr) * Double.parseDouble(heightStr) * Long.parseLong(numStr);
                            //立方厘米 转 立方米
                            tmepVolumn = tmepVolumn / 1000000;
                            if (tmepVolumn <= 0.01) {
                                tmepVolumn = 0.01;
                            }
                            //四舍五入，保留两位
                            allVolumn += roundingNum(tmepVolumn, 2);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            showToast("数据异常！");
                            return;
                        }
                    }
                }
                tvAllVolume.setText(allVolumn + "");
            }
        });

        btnOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String allVolume = tvAllVolume.getText().toString().trim();
                if (!allVolume.equals("")) {
                    double tempVolume = Double.parseDouble(allVolume);
                    if (tempVolume >= 0 && tempVolume <= 999999) {
                        mAllVolume.setText(allVolume);
                    } else {
                        //总值不超过999999kg
                        showToast("总值不可超过999999m³");
                        return;
                    }
                }
                dialog.dismiss();
            }
        });

        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /***
     * 体积计算中的子布局
     */
    private LinearLayout getVolumnLayoutItem() {
        LinearLayout layoutItem = (LinearLayout) LayoutInflater.from(CheckBalanceActivity.this).inflate(R.layout.volumn_calculation_item, null);
        return layoutItem;
    }

    /**
     * 四舍五入
     *
     * @param data 被四舍五入的数据
     * @param num  保留位数
     */
    private double roundingNum(double data, int num) {
        //四舍五入
        BigDecimal b = new BigDecimal(data);
        return b.setScale(num, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 获取复秤合计和差重差方数据
     */
    private void getDataCount() {
        //获取所有复秤数据
        List<CheckBalanceTable> balanceTableList = checkBalanceTableDao.findAll();
        if (balanceTableList != null && balanceTableList.size() > 0) {
            mTvAllCount.setText(balanceTableList.size() + "");
        } else {
            mTvAllCount.setText("0");
        }
        //获取所有差重差方数据
        List<CheckBalanceTable> diffLists = checkBalanceTableDao.getDiffData();
        if (diffLists != null && diffLists.size() > 0) {
            mTvAllDiff.setText(diffLists.size() + "");
        } else {
            mTvAllDiff.setText("0");
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
        if ((view.getId() == R.id.check_balance_remark)) {
            if (canVerticalScroll(mRemark)) {
                view.getParent().requestDisallowInterceptTouchEvent(true);
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    view.getParent().requestDisallowInterceptTouchEvent(false);
                }
            } else {
                view.getParent().requestDisallowInterceptTouchEvent(false);
            }
        }
        return false;
    }

    /**
     * EditText竖直方向是否可以滚动
     *
     * @param editText 需要判断的EditText
     * @return true：可以滚动   false：不可以滚动
     */
    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;
        if (scrollDifference == 0) {
            return false;
        }
        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }
}
